package cn.tedu._03vehicle.base.exception;

import cn.tedu._03vehicle.base.response.JsonResult;
import cn.tedu._03vehicle.base.response.StatusCode;
import jakarta.validation.ConstraintViolationException;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;
import org.springframework.web.multipart.MaxUploadSizeExceededException;
import org.springframework.web.server.MethodNotAllowedException;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

@Slf4j
@RestControllerAdvice
public class GlobalExceptionHandler {
	@ExceptionHandler(IllegalArgumentException.class)
	public JsonResult doHandleIllegalArgumentException(IllegalArgumentException ex){
		//获取异常提示消息: throw new IllegalArgumentException("车辆id不能小于0");
		String data = ex.getMessage();
		//打印日志
		log.error("IllegalArgumentException:" + data);
		//{"state":3000, "message":"操作失败", "data":"车辆id不能小于0"}
		return new JsonResult(StatusCode.OPERATION_FAILED, data);
	}
	
	@ExceptionHandler(RuntimeException.class)
	public JsonResult doHandleRuntimeException(RuntimeException ex){
		String data = ex.getMessage();
		log.error("RuntimeException:" + data);
		return new JsonResult(StatusCode.OPERATION_FAILED, data);
	}

	@ExceptionHandler(MethodArgumentNotValidException.class)
	public JsonResult doHandleMethodArgumentNotValidException(MethodArgumentNotValidException ex){
		//获取封装参数异常提示消息:ex.getFieldError().getDefaultMessage()
		String data = ex.getFieldError().getDefaultMessage();
		log.error("MethodArgumentNotValidException:" + data);
		return new JsonResult(StatusCode.VALIDATED_ERROR, data);
	}
	@ExceptionHandler(ConstraintViolationException.class)
	public JsonResult doHandleConstraintViolationException(ConstraintViolationException ex){
		String data = ex.getMessage().split(":")[1].trim();
		log.error("ConstraintViolationException:" + data);
		return new JsonResult(StatusCode.VALIDATED_ERROR, data);
	}
	@ExceptionHandler(MaxUploadSizeExceededException.class)
	public JsonResult doHandleMaxUploadSizeExceededException(MaxUploadSizeExceededException ex){
		String data = "上传文件超出大小限制";
		log.error("MaxUploadSizeExceededException:" + data);
		return new JsonResult(StatusCode.FILE_UPLOAD_ERROR, data);
	}

//	@ExceptionHandler(RuntimeException.class)
//	public JsonResult doHandleRuntimeException(RuntimeException ex) {
//		String data = ex.getMessage();
//		log.error("RuntimeException:"+ data);
//		return new JsonResult(StatusCode.OPERATION_FAILED, data);
//	}
	
}